<script setup>
import {reactive, ref} from "vue";
import {md5} from "js-md5"
import {doPostJson} from "../util/HttpClient.js";
import {ElMessage} from "element-plus";
import router from "../router/router.js";

//定义form表单中中 ref="loginform"引用对象
const loginform = ref()

//定义验证规则
let rules = reactive({
  //验证登录的账号
  loginName: [
    {required: true, message: '请输入用户名', trigger: 'blur'},
  ],
  //验证登录密码
  loginPwd: [
    {required: true, message: '请输入登录密码', trigger: 'blur'},
    {min: 6, max: 16, message: '登录密码长度为6-16位', trigger: 'blur'},
  ]

})

//定义表单
const form = reactive({
  loginName: 'admin',
  loginPwd: '111aaa',

})

//登录
const onLogin = async (frm) => {
  if (!frm) {
    return
  }

  await frm.validate((valid) => {
    if (valid) {
      //可以提交请求
      form.loginPwd = md5(form.loginPwd)
      doPostJson('/operator/login', form).then((resp) => {
        if (resp.data.code == 1000) {
          ElMessage.success(resp.data.msg)
          //存储jwt到SessionStorage对象
          window.sessionStorage.setItem('BOSS_TOKEN', JSON.stringify(resp.data.data))
          //跳转页面
          router.push({ path: '/frame' })
        }
      })
    } else {
      ElMessage.warning('登录名称或密码格式错误')
    }
  })
}

//重置
const onReset = () => {
  form.loginName = ''
  form.loginPwd = ''

}
</script>

<template>
  <div style="margin-top: 240px; margin-left: 480px">
    <el-row :gutter="20">
      <el-col :span="2" :offset="0">
        <img src="../assets/powerLogo.png" width="125" height="125"/>
      </el-col>
      <el-col :span="6" :offset="1">
        <el-form :model="form"
                 ref="loginform"
                 :rules="rules"
                 label-width="80px"
                 :inline="false">
          <el-form-item label="登录名称" prop="loginName">
            <el-input v-model="form.loginName"></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="loginPwd">
            <el-input v-model="form.loginPwd" type="password"></el-input>
          </el-form-item>
          <el-form-item>
            <el-space :size="30">
              <el-button type="success" round @click="onLogin(loginform)">登录</el-button>
              <el-button type="warning" round @click="onReset">重置</el-button>
            </el-space>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped>

</style>